<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Attachment;
use app\common\model\Pay;
use fast\Random;
use think\Db;
use think\Exception;
use think\Log;

/**
 *  一键援助
 */
class Rescue extends Api
{
    protected $noNeedRight = '*';

    /**
     * 发布救援信息
     * @return void
     */
    public function add()
    {
        try {
            $params = $this->request->post();
            extract($params);
            if(empty($lng) || empty($lat) || empty($describe) || empty($mobile) || empty($name) || empty($license_plate_number) || empty($images)){
                $this->error(__('Parameter %s can not be empty',''));
            }
            $params['user_id'] = $this->auth->id;
            $artificer = (new \app\common\model\Artificer())->seek($lng,$lat);
            if($artificer){
                $params['artificer_id'] = $artificer;
                $params['distribution_status'] = '20';
                $params['distributiontime'] = time();
                $artificerInfo = \app\common\model\Artificer::get($artificer);
                if($artificerInfo && $artificerInfo->lat && $artificerInfo->lng){
                    $distance = GetDistance($lat,$lng,$artificerInfo->lat,$artificerInfo->lng,2,1);
                    $extend = (new \app\common\model\order\Rescue())->getPrice($distance);
                    $params = array_merge($params,$extend);
                }
            }
            $result = \app\common\model\order\Rescue::create($params);
            if($result !== false){
                $this->success(__('Operation completed'));
            }
            $this->success(__('Operation failed'));
        }catch (Exception $e){
            Log::write($e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 订单列表
     * @return void
     */
    public function list()
    {
        try {
            $limit = $this->request->post('limit/d',10);
            $page = $this->request->post('page/d',1);
            $where = [
                'user_id' => ['=',$this->auth->id]
            ];
            $model = new \app\common\model\order\Rescue();
            $list = $model->list($where,$limit,$page);
            if($list === false){
                $this->error($model->getError());
            }
            $this->success(__('success'),$list);
        }catch (Exception $e){
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 订单详情
     * @return void
     */
    public function orderInfo()
    {
        try {
            $id = $this->request->post('id/d');
            $model = new \app\common\model\order\Rescue();
            $data = $model->details($id);
            if($data === false){
                $this->error($model->getError());
            }
            if($data->user_id !== $this->auth->id){
                $this->error('参数错误');
            }
            $this->success(__('success'),$data);
        }catch (Exception $e){
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 取消订单  （技工未接单，无责取消；技工已接单，有责取消）
     * @return void
     */
    public function cancel()
    {
        Db::startTrans();
        try {
            $id = $this->request->post('id/d');
            $pay_way = $this->request->post('pay_way');  // 支付方式:10=微信支付,20=支付宝支付,30=余额支付
            $model = new \app\common\model\order\Rescue();
            $row = $model->details($id);
            if($row === false){
                $this->error($model->getError());
            }
            //order_status   订单状态:10=进行中,20=已完成,30=已取消
            if(($row->user_id !== $this->auth->id) || ($row->order_status != '10')){
                $this->error('参数错误');
            }
            //未接单  无责取消
            if($row->take_status == '10'){
                $row->order_status = '30';
                $row->canceltime = time();
                $row->allowField(true)->save();
                $msg = __('Operation completed');
                $data = [];
            }
            // 技工已接单，有责取消
            if($row->take_status == '20'){
                if(empty($pay_way) || !in_array($pay_way,['10','20','30'])){
                    $this->error('有责取消，需要支付违约金');
                }

                //duty_status 有责取消订单:10=否,20=是
                $row->duty_status = '20';
                $row->pay_way = $pay_way;
                $row->allowField(true)->save();

                $payTypeArr = ['10'=>'wechat','20'=>'alipay'];
                if(!isset($payTypeArr[$pay_way])){
                    $this->error('支付类型错误');
                }
                $payModel = new Pay();
                $data = $payModel->createPay($this->auth->id,4,$id,$payTypeArr[$pay_way],'api/index/notify/paytype/'.$payTypeArr[$pay_way],'','有责取消援助');
                if($payModel->hasError()){
                    $this->error($payModel->getError());
                }
                $msg = '去支付';
                //测试 回调
                $payModel->notify($data,Random::alnum(18));
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
        $this->success($msg,$data);
    }

    /**
     * 完成订单，支付
     * @return void
     */
    public function pay()
    {

    }

    /**
     * 删除订单
     * @return void
     */
    public function del()
    {

    }
}